import EventManager from "../../Common/EventManager";
import { EventType } from "../../GameSpecial/GameEventType";
import Frame from "../frameNamespace";
import { GAME_MODE } from "../other/game/gameMode_Json";
import UserService from "../services/userService";
import UMe, { mgrs, sers } from "../system/OverallSystem ";

const { ccclass, property } = cc._decorator;

interface loadAssetInfo {
    bundleKey: Frame.BundleName;
    name: string;
}

@ccclass
export default class Loading extends cc.Component {

    @property({ type: cc.ProgressBar, displayName: "整体进度条" })
    private totalBar: cc.ProgressBar = null;

    @property({ type: cc.ProgressBar, displayName: "单次进度条" })
    private onceBar: cc.ProgressBar = null;

    @property({ type: cc.Label, displayName: "加载文本" })
    private lbLoad: cc.Label = null;

    private totalCnt: number = 0;
    private completedCnt: number = 0;


    @property(cc.Node)
    tishi:cc.Node = null

    @property(cc.Node)
    kuaishouruanzhu:cc.Node=null

    onLoad() {
        if (cc.sys.platform == cc.sys.ANDROID){
            this.tishi.active = true
        }

        if(cc.sys.platform ==cc.sys.VIVO_GAME){
            this.tishi.active = true
        }

        window['user_id'] = ''
        window['LookCnt'] = 0
        if((cc.sys.platform == cc.sys.BYTEDANCE_GAME||cc.sys.platform == cc.sys.BYTEDANCE_GAME_SUB) && window['tt']){
            this.initSdk()
            // console.log('zs_network init')
        }

        if(window['ks']){
            this.kuaishouruanzhu.active = true
        }


        this.Init();
    }

    async initSdk(){
        // await zs_sdk.zs_network.init()
        // console.log('zs_network init')
        // console.log(zs_sdk.zs_network.loginInfo.user_id)
        // console.log(zs_sdk.zs_network.loginInfo.is_white_list)
        // if(zs_sdk.zs_network.loginInfo.is_white_list==1){
        //     window['GM-mode'] = true
        // }
        // window['user_id'] = zs_sdk.zs_network.loginInfo.user_id || ''
    }

    start() {
        this.node.getComponent(cc.Canvas).fitHeight = UserService.IPAD
        this.node.getComponent(cc.Canvas).fitWidth = !UserService.IPAD
       
    }

    //需要提前 预加载 的 bundle 资源列表
    private loadAssetList: loadAssetInfo[] = [
        {
            bundleKey: Frame.BundleName.loadingPage,
            name: "游戏加载页面",
        },
        {
            bundleKey: Frame.BundleName.Sound,
            name: "游戏音频资源",
        },
        // {
        //     bundleKey: Frame.BundleName.Game,
        //     name: "游戏资源",
        // },
        // {
        //     bundleKey: Frame.BundleName.Home,
        //     name: "游戏初始场景资源",
        // },
    ];

    private async Init() {
        this.totalBar.progress = 0;
        this.onceBar.progress = 0;

        console.group("加载bundle");

        UMe.InitBundle();
        this.totalCnt += UMe.Managers.bundleMgr.getLength();
        this.totalCnt += (this.loadAssetList.length + 1);
        //加载bundle
        this.updateLoadLabel("加载游戏...");
        await UMe.Managers.bundleMgr.loadAllBundle(this.updateTotalBar.bind(this));

        //加载游戏框架资源
        await this.loadAllFrameAsset();

        console.log("-----加载bundle完毕-----");
        console.groupEnd();

        //预加载初始场景,home场景or自选场景
        this.loadBeginningScener().then((loadScene) => {
            this.updateTotalBar();
            UMe.loadScene(loadScene);
        }).catch((loadScene) => {
            // IphaOS.loadScene(loadScene);
        });
    }

    /** 预加载全部框架资源 */
    private async loadAllFrameAsset() {
        for await (const elem of this.loadAssetList) {
            this.updateLoadLabel(elem.name);
            await this.loadPreloadAsset(elem.bundleKey, elem.name);
            this.updateTotalBar();
        }
    }

    private loadPreloadAsset(bundleKey: string, name: string) {
        return new Promise<void>((resolve, reject) => {
            UMe.Managers.bundleMgr.BundleList[bundleKey].preloadDir("preload", this.updateOnceBar.bind(this), (error, items) => {
                if (error) {
                    reject();
                    console.error(name + "---加载失败!!", error);
                    return;
                }
                // this.scheduleOnce(() => {
                resolve();
                // }, 1);
            });
        });
    }

    private loadBeginningScener() {
        return new Promise<string>((resolve, reject) => {
            this.updateLoadLabel("加载游戏初始场景");


            if(window['tt'] || window['wx']){
                let t = window['tt'] || window['wx']
                t.onShow((res) => {
                    console.log("启动参数如下：", res.query);
                    console.log("来源信息如下：", res.refererInfo);
                    console.log("启动场景：", res.scene);
                    if(res.scene == '101001' || res.scene == '021036'){
                        window['sceneCode'] = res.scene
                        EventManager.emit(EventType.UIEvent.showCheckSceneBtn)
                    }
                    if(mgrs().soundMgr.isPlayMusic){
                        console.log('播放音乐')
                        mgrs().soundMgr.playMusic(mgrs().soundMgr.shangyige);
                    }
                });
            }


            // if(window['tt'] || window['wx']){
            //     mgrs().gameMgr.enterMode(GAME_MODE.MAJIANG,false);
            //     return
            // }

            sers().uiSrv.showLoding(true);

            let loadScene: string = "home";
            cc.director.preloadScene(loadScene, this.updateOnceBar.bind(this), (err) => {
                if (err) {
                    reject(loadScene);
                    console.error("预加载初始场景失败!!", err);
                    return;
                }
                // this.scheduleOnce(() => {
                resolve(loadScene);
                // }, 1);
            });
           

           
            // mgrs().gameMgr.enterMode(GAME_MODE.PUKEPAI);
        });
    }

    private updateTotalBar() {
        this.completedCnt++;
        this.totalBar.progress = (this.completedCnt) / this.totalCnt;
        this.totalBar.node.children[0].children[0].x = (this.completedCnt) / this.totalCnt * 567 -567/2

    }
    private updateOnceBar(completedCount: number, totalCount: number, item: any) {
        this.onceBar.progress = completedCount / totalCount;

    }
    private updateLoadLabel(str: string) {
        this.lbLoad.string = str;
    }

    update(dt) {

    }
}
